import {
  ref, computed, Transition, reactive, onMounted, nextTick, onBeforeUnmount
} from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import { GetAddUserProfilingTaskBase, AddUserProfilingTask, GetUserProfilingTaskList, GetCustomerInfo, GetAddUserProfileChartBaseData, GetChartData, AddUserProfileChart } from "@/api/stu/bankBigData";
import { emitter } from "@/utils/mitt";
import { Column, BidirectionalBar, Line, RadialBar, Area, Radar, Rose, Scatter, Bar } from "@antv/g2plot";
import { log } from "console";
export function usePortrait() {
  const dataList = ref();
  const dataList2 = ref()
  const chartList = ref()
  const echartesnum = ref([]);
  const selectId = ref()
  const route = useRoute();
  const router = useRouter();
  //新建指标数据
  const selectData = ref()
  const taskTitlt = ref()
  const customerName = ref()
  const chartFormData = reactive({
    chartName: '',
    dimension: '',
    indexStr: '',
    chartType: '',
    countDataType: '',
  })
  const formData = reactive({
    taskTittle: '',
    customerName: '',
    portraitIndexSystemId: '',
  })
  const taskTittleRegex = /^[\u4e00-\u9fa5]{0,50}$/;// 校验中文
  const customerNameRegex = /^[\u4e00-\u9fa5]{4,12}$/
  const addChartTitle = /^[^ \u0021-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]{0,50}$/ //50个字符
  const loading = ref<boolean>(false);
  const tableRef = ref()
  const createTaskVisible = ref<boolean>(false);
  const addProVisible = ref<boolean>(false);
  const tLoding = ref<boolean>(false)
  const parameterValueMap = {
    1: ">",
    2: "=",
    3: "<",
    4: ">=",
    5: "<=",
    6: "≠",
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });

  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
    },
    {
      label: "姓名",
      prop: "name"
    }, {
      label: "年龄",
      prop: "age"
    }, {
      label: "性别",
      prop: "gender",
    }, {
      label: "工作类型",
      prop: "jobType"
    },
    {
      label: "是否按时还款",
      prop: "ontimeRepayment",
      minWidth: 150
    },
    {
      label: "还款频率",
      prop: "repaymentFrequency",
    }, {
      label: "是否有逾期或拖欠",
      prop: "isOverdue",
      minWidth: 150
    }, {
      label: "借款次数（次）",
      prop: "numberOfLoans",
      minWidth: 150,
    }, {
      label: "借款用途",
      prop: "loanPurposes"
    },
    {
      label: "信用卡使用频率",
      prop: "creditCardUseFrequency",
      minWidth: 150
    },
    {
      label: "借贷履约记录",
      prop: "lendingContractRecord",
      minWidth: 150,
    }, {
      label: "借款总额（万元）",
      prop: "totalLoanAmount",
      minWidth: 150,

    }, {
      label: "贷款余额（万元）",
      prop: "loanBalance",
      minWidth: 150,

    }, {
      label: "是否有催收记录",
      prop: "collectionRecord",
      minWidth: 150
    },
    {
      label: "恶意透支次数（次）",
      prop: "maliciousOverdraftTimes",
      minWidth: 150
    },
    {
      label: "近期是否有多次申请借贷",
      prop: "recentMultipleLoanApplications",
      minWidth: 200
    }, {
      label: "电信欠费频率",
      prop: "telecomOverdueFrequency",
      minWidth: 150
    }, {
      label: "是否在电信黑名单",
      prop: "blacklistStatus",
      minWidth: 150
    }, {
      label: "社保是否连续",
      prop: "continuousnessOverduePayments",
      minWidth: 150
    },
    {
      label: "是否存在断缴或缴费不足",
      prop: "paymentInterruptionsOrInsufficiencies", minWidth: 250
    },
    {
      label: "不动产",
      prop: "realEstate",
    }, {
      label: "证券（万元）",
      prop: "securities",
      minWidth: 150,

    }, {
      label: "基金（万元）",
      prop: "funds",
      minWidth: 150,

    }, {
      label: "保险（万元）",
      prop: "insurance",
      minWidth: 150,

    },
    {
      label: "现金（万元）",
      prop: "cash",
      minWidth: 150,

    },
    {
      label: "变现能力",
      prop: "liquidity"
    }, {
      label: "信用飞违约次数（次）",
      prop: "defaultTime",
      minWidth: 200
    }, {
      label: "是否在航旅黑名单",
      prop: "isblacklist",
      minWidth: 200
    },
    {
      label: "已取得的最高学历",
      prop: "educationLevel",
      minWidth: 200
    },
    {
      label: "有无继续教育打算",
      prop: "continuingEducationWillingness",
      minWidth: 200
    }, {
      label: "社交活跃度",
      prop: "socialActivity"
    }, {
      label: "网购频率",
      prop: "onlineShoppingFrequency",
    }, {
      label: "游戏时长",
      prop: "gamingHours"
    },
    {
      label: "是否有固定的工作",
      prop: "employmentStatus",
      minWidth: 200
    }, {
      label: "是否有其他稳定收入",
      prop: "additionalIncome",
      minWidth: 200
    },
    {
      label: "月收入（元）",
      prop: "monthlyIncome",
      minWidth: 150,

    },
  ];
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    }, {
      label: "画像任务名称",
      prop: "userTaskName"
    }, {
      label: "客户群",
      prop: "customerGroupName",
    },
    {
      label: "详情",
      prop: "operation",
      width: 180,
      slot: "operation"
    },
  ];
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }
  const handleCurrentChange = val => {
    getList()
  };
  function handleSizeChange() {
    getList()
  }
  //点击选中列表行
  async function onRowClick(row) {
    selectId.value = row.userPortraitId
    taskTitlt.value = row.userTaskName
    customerName.value = row.customerGroupName
    getList2()
  }
  //获取选中列表下的人数
  async function getList2() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination2.currentPage,
      pageCount: pagination2.pageSize,
      detailId: selectId.value,
    };
    let res = await GetCustomerInfo(data)
    if (res.success) {
      dataList2.value = res?.data.items
      pagination2.total = res?.data.totalCount
    } else {
      ElMessage.error(res.msg);
    }
  }
  const handleCurrentChange2 = val => {
    getList2()
  };
  function handleSizeChange2() {
    getList2()
  }
  async function checkPor(row) {
    selectId.value = row.userPortraitId
    taskTitlt.value = row.userTaskName
    customerName.value = row.customerGroupName
    let data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      detailId: selectId.value,
    }
    let res = await GetChartData(data)
    if (res.success) {
      tLoding.value = true
      chartList.value = res?.data.userChartList
      if (res.data?.eightChartData.length) {
        res.data?.eightChartData.forEach(item => {
          chartList.value.unshift(item)
        })
      }
      //如果有八维就把他push到头部
      console.log(chartList.value);

      chartList.value.forEach((item, index) => {
        switch (Number(item.chartType)) {
          case 1:
            //堆叠折线图
            Multilinechart(item, index)
            break;
          case 2:
            //堆叠面积图
            Scopeareachart(item, index)
            break;
          case 3:
            //叠柱柱状图
            stackedbarchart(item, index);
            break;
          case 4:
            //堆叠条形图
            multipleseriesbarchart(item, index)
            break;
          case 5:
            //极坐标扇形图
            rosePlot(item, index)
            break;
          case 6:
            //极坐标柱状图
            rdaialBarChart(item, index)
            break;
          case 7:
            //八维雷达图
            eightChart(item, index)
            break;
        }
      });
    } else {
      ElMessage.warning('请先添加画像')
    }
  }
  async function Multilinechart(row, num) {

    const domStr = "domStr" + num;
    const data = row.indexDataList
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const line = new Line(domStr, {
      data,
      xField: 'x',
      yField: 'y',
      seriesField: 'indexName',
      xAxis: {
        // title: {
        //   text: row.chartName
        // }
      },
      yAxis: {
        label: {
          // 数值格式化为千分位
          formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`),
        },
      },
    });

    line.render();
  }
  async function Scopeareachart(row, num) {
    const domStr = "domStr" + num;
    const data = row.indexDataList
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const area = new Area(domStr, {
      data,
      xField: 'x',
      yField: 'y',
      seriesField: 'indexName'
    });
    area.render();
  }
  async function multipleseriesbarchart(row, num) {
    const domStr = "domStr" + num;
    const data = row.indexDataList
    //把该类型图标需要的数据根据timeValue匹配
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const stackedColumnPlot = new Bar(domStr, {
      data: data.reverse(),
      isStack: true,
      xField: "y",
      yField: "x",
      seriesField: "indexName",
      yAxis: {

      },
      xAxis: {

      },
      label: {
        // 可手动配置 label 数据标签位置
        position: "middle", // 'top', 'bottom', 'middle'
        // 可配置附加的布局方法
        layout: [
          // 柱形图数据标签位置自动调整
          { type: "interval-adjust-position" },
          // 数据标签防遮挡
          { type: "interval-hide-overlap" },
          // 数据标签文颜色自动调整
          { type: "adjust-color" },
        ],
      },
    });
    stackedColumnPlot.render();
  }

  async function stackedbarchart(row, num) {
    const domStr = "domStr" + num;
    const data = row.indexDataList
    //把该类型图标需要的数据根据timeValue匹配
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const stackedColumnPlot = new Column(domStr, {
      data,
      isGroup: true,
      xField: "x",
      yField: "y",
      seriesField: "indexName",
      yAxis: {

      },
      xAxis: {

      },
      label: {
        // 可手动配置 label 数据标签位置
        position: "middle", // 'top', 'bottom', 'middle'
        // 可配置附加的布局方法
        layout: [
          // 柱形图数据标签位置自动调整
          { type: "interval-adjust-position" },
          // 数据标签防遮挡
          { type: "interval-hide-overlap" },
          // 数据标签文颜色自动调整
          { type: "adjust-color" },
        ],
      },
    });
    stackedColumnPlot.render();
  }

  async function rosePlot(row, num) {
    const domStr = "domStr" + num;
    const data = row.indexDataList
    //把该类型图标需要的数据根据timeValue匹配
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const stackedColumnPlot = new Rose(domStr, {
      data,
      xField: 'x',
      yField: 'y',
      isStack: true,
      // 当 isStack 为 true 时，该值为必填
      seriesField: 'indexName',
      radius: 0.9,
      label: {
        offset: -15,
      },
      interactions: [
        {
          type: 'element-active',
        },
      ],
    });
    stackedColumnPlot.render();
  }

  async function rdaialBarChart(row, num) {
    const domStr = "domStr" + num;
    const data = row.indexDataList
    //把该类型图标需要的数据根据timeValue匹配
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const stackedColumnPlot = new RadialBar(domStr, {
      data,
      xField: 'x',
      yField: 'y',
      colorField: 'type',
      isStack: true,
      maxAngle: 270,
    });
    stackedColumnPlot.render();
  }

  async function eightChart(row, num) {
    console.log(row, num);

    const domStr = "domStr" + num;
    const data = row.radarChartData
    //把该类型图标需要的数据根据timeValue匹配
    echartesnum.value.push({
      title: row.chartName,
      data: "domStr" + num,
    });
    echartesnum.value = Array.from(new Set(echartesnum.value));
    await nextTick();
    const stackedColumnPlot = new Radar(domStr, {
      data,
      xField: 'indexName',
      yField: 'indexValue',
      appendPadding: [5, 10, 0, 10],
      meta: {
        indexValue: {
          min: 0,
          nice: true,
        },
      },
      area: {},
      autoFit: true,
      // seriesField: 'indexCode',
      // xAxis: {
      //   line: null,
      //   tickLine: null,
      //   grid: {
      //     line: {
      //       style: {
      //         lineDash: null,
      //       },
      //     },
      //   },
      // },
      point: {
        size: 2,
      },
    });
    stackedColumnPlot.render();
  }

  function saveCreate() {
    if (taskTittleRegex.test(formData.taskTittle) == false) {
      ElMessage({
        showClose: false,
        message: '任务名称应该输1 - 50个汉字',
        type: 'warning',
        duration: 500,
      })
      return
    }
    if (customerNameRegex.test(formData.customerName) == false) {
      ElMessage({
        showClose: false,
        message: '客群名称应该输4 - 15个汉字',
        type: 'warning',
        duration: 500,
      })
      return
    }
    BtnLoading.value = true
    OUTBtnLoding()
    emitter.emit("CreateCustomer")
  }

  onBeforeUnmount(() => {
    emitter.off("saveCustomer")
  })
  //创建任务
  emitter.on("saveCustomer", async (row) => {
    const data = JSON.parse(row)
    const resultParams = {
      planId: route.query.planId,
      taskId: route.query.taskId,
      userTaskName: formData.taskTittle,
      customerGroupName: formData.customerName,
      portraitIndexSystemId: formData.portraitIndexSystemId,
      customerScreening: []
    }
    data.forEach(item => {
      const outerLayerId = item['id'][0];
      const isPresent = resultParams.customerScreening.find(obj => obj.id == outerLayerId);

      if (isPresent) {
        addToOperatorsInfoList(isPresent.operatorsInfoList, item);
      } else {
        const outerLayer = {
          id: outerLayerId,
          operatorsInfoList: []
        };
        addToOperatorsInfoList(outerLayer.operatorsInfoList, item);
        resultParams.customerScreening.push(outerLayer);
      }
    });
    const json = {
      userTaskName: resultParams.userTaskName,
      customerGroupName: resultParams.customerGroupName,
      customerScreening: resultParams.customerScreening,
    }
    resultParams.studentAnswer = JSON.stringify(json)
    resultParams.customerScreening.forEach(obj => {
      delete obj.id;
    });
    let res = await AddUserProfilingTask(resultParams)
    if (res.status == 200) {
      ElMessage.success(res.msg);
      createTaskVisible.value = false
      for (let variable in formData) {
        formData[variable] = '';
      }
    } else {
      ElMessage.error(res.msg);
    }
    setTimeout(() => {
      getList()
    }, 1000)
  })

  //解析多层筛选数据
  function addToOperatorsInfoList(operatorsInfoList, item) {
    if (item.mType == 3) {
      operatorsInfoList.push({
        "fieldName": item.mName,
        "fieldType": 1,
        "operatorsList": [
          {
            "parameterValue": item.selectMore.join('|'),
            "operatorsStr": item.rather == 1 ? '包含' : '不包含'
          }
        ]
      })
    } else {
      operatorsInfoList.push({
        "fieldName": item.term,
        "fieldType": 2,
        "operatorsList": [
          {
            "parameterValue": Number(item.times),
            "operatorsStr": parameterValueMap[item.rather]
          },
          {
            "parameterValue": Number(item.times2),
            "operatorsStr": parameterValueMap[item.rather2],
          },
        ]
      })
    }
  }

  //获取任务列表
  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
    };
    const respone = await GetUserProfilingTaskList(data);
    if (respone.success) {
      dataList.value = respone?.data.items
      pagination.total = respone.data.totalCount;
    } else {
      ElMessage.error(respone.msg);
    }
  }
  //打开添加图像弹窗
  function addChart() {
    if (selectId.value) {
      addProVisible.value = true
    } else {
      ElMessage.warning('请先点击列表选择你要添加画像的任务')
    }
  }
  async function saveNewChart() {
    if (addChartTitle.test(chartFormData.chartName) === false) {
      ElMessage.error('任务名称应该请输1 - 50个字符')
      return
    }
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      userPortraitId: selectId.value,
      chartName: chartFormData.chartName,
      dimension: chartFormData.dimension,
      indexStr: chartFormData.indexStr ? chartFormData.indexStr.join('|') : '',
      chartType: chartFormData.chartType,
      countDataType: chartFormData.countDataType,
      studentAnswer: JSON.stringify(chartFormData)
    }
    BtnLoading.value = true
    OUTBtnLoding()
    let res = await AddUserProfileChart(data)
    if (res.status == 200) {
      ElMessage.success(res.msg);
      addProVisible.value = false
      for (let variable in chartFormData) {
        chartFormData[variable] = '';
      }
    } else {
      ElMessage.error(res.msg);
    }

  }

  function cancelAddChart() {
    addProVisible.value = false
    for (let variable in chartFormData) {
      chartFormData[variable] = '';
    }
  }
  function handleCancelShowChart() {
    tLoding.value = false
    echartesnum.value = []
    console.log(echartesnum.value);

  }
  onMounted(async () => {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    };
    let res = await GetAddUserProfileChartBaseData(data)
    if (res.success) {
      selectData.value = res?.data
    } else {
      ElMessage.error(res.msg);
    }
    getList()
  })


  function cancelCreate() {
    createTaskVisible.value = false
    formData.taskTittle = '',
      formData.customerName = '',
      formData.portraitIndexSystemId = ''
  }


  return {
    columns,
    tableRef,
    loading,
    dataList,
    dataList2,
    pagination,
    chartFormData,
    createTaskVisible,
    addProVisible,
    formData,
    pagination2,
    columns2,
    selectData,
    taskTitlt,
    customerName,
    tLoding,
    echartesnum,
    handleSizeChange,
    handleCurrentChange,
    handleSizeChange2,
    handleCurrentChange2,
    checkPor,
    onRowClick,
    addChart,
    saveNewChart,
    cancelAddChart,
    chartList,
    handleCancelShowChart,
    cancelCreate,
    saveCreate,
    BtnLoading,
  }
}
